package com.funymmz.demo.webapi;


import com.funymmz.demo.domain.User;
import com.funymmz.demo.service.UserService;
import com.funymmz.demo.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/webapi/user")
public class UserRestController {

    @Autowired
    private UserService userService;

    /**
     * 获取所有用户
     * @return 用户列表
     */
    @GetMapping("/list")
    public List<User> getAll(){
        return userService.findAll();
    }

    /**
     * 分页读取用户信息
     * @param page page
     * @param size size
     * @param name name
     * @return 分页结果
     */
    @GetMapping("/getByPage")
    public PageUtils getByPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                               @RequestParam(value = "size", defaultValue = "10") Integer size,
                               @RequestParam(value = "name", defaultValue = "") String name){
        //按id排倒序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");

        Page<User> userPage;

        if (StringUtils.isEmpty(name)){
            Pageable pageable = PageRequest.of(page,size,sort);
            userPage = userService.findAll(pageable);
        }
        else {
            User user = new User();
            user.setUsername(name);

            Pageable pageable = PageRequest.of(0,10,sort);
            //全部模糊查询，即%{name}%
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<User> example = Example.of(user, matcher);

            userPage = userService.findAll(example, pageable);
        }
        return new PageUtils(userPage.getContent(), userPage.getTotalElements());
    }

    /**
     * 通过id获取用户
     * @param id id
     * @return 用户
     */
    @GetMapping("/get")
    public User get(Long id){
        return userService.getById(id);
    }

    /**
     * 插入用户
     * @param user 用户
     * @return 用户
     */
    @PostMapping("/insert")
    public User insert(User user){
        return userService.insert(user);
    }

    /**
     * 更新用户信息
     * @param user 用户
     * @return 用户
     */
    @PutMapping("/update")
    public User update(User user){

        //读取旧的数据
        User oldUser = userService.getById(user.getId());
        if (StringUtils.isEmpty(user.getPassword())){
            //没有新密码就那么就是旧密码
            user.setPassword(oldUser.getPassword());
        }
        user = userService.update(user);
        return user;
    }

    /**
     * 通过id删除用户
     * @param id id
     */
    @DeleteMapping("/delete")
    public void delete(Long id){
        userService.delete(id);
    }
}
